<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import AppHeader from '@/components/layout/AppHeader.vue'
import LeftSidebar from '@/components/layout/LeftSidebar.vue'
import { useAuthStore } from '@/stores/auth'
import { HOME_SECTIONS, type HomeSection } from '@/constants/HOME'
import { api } from '@/utils/request'

const auth = useAuthStore()
const router = useRouter()

onMounted(async () => {
  // 尝试获取用户信息，但不强制要求登录
  if (!auth.user) await auth.fetchMe()
})

const currentSection = ref<HomeSection>(HOME_SECTIONS.HOME)

interface PointPackage {
  id: string
  title: string
  points: number
  price: number
  badge?: string
  img?: string
}

const pointPackages = ref<PointPackage[]>([])

// 从后端加载积分商品包
async function fetchPointPackages() {
  try {
    const res = await api.get('/api/pay/point-packages')
    if (res.ok) {
      const data = await res.json()
      // 转换后端数据格式为前端需要的格式
      pointPackages.value = data
        .filter((pkg: any) => pkg.isActive) // 只显示启用的商品包
        .sort((a: any, b: any) => a.sortOrder - b.sortOrder) // 按排序顺序排列
        .map((pkg: any) => ({
          id: pkg.id,
          title: pkg.name,
          points: Number(pkg.pointsAmount),
          price: Number(pkg.priceDecimal),
          badge: pkg.badge,
          img: pkg.imageUrl || `https://picsum.photos/120?${pkg.id}` // 如果没有图片则使用默认图片
        }))
    }
  } catch (error) {
    console.error('포인트 상품 패키지 로드 실패:', error)
    // 如果加载失败，使用默认数据
    pointPackages.value = [
      { id: 'p100', title: '100,000 원 + 동메달', points: 100000, price: 100000, img: 'https://picsum.photos/120?1' },
      { id: 'p200', title: '200,000 원 + 은메달', points: 200000, price: 200000, img: 'https://picsum.photos/120?2' },
      { id: 'p300', title: '300,000 원 + 플래티넘', points: 300000, price: 300000, img: 'https://picsum.photos/120?3' },
      { id: 'p500', title: '500,000 원 + 다이아몬드', points: 500000, price: 500000, img: 'https://picsum.photos/120?4' },
    ]
  }
}

const bankAccount = ref<any | null>(null)

const showModal = ref(false)
const selected = ref<PointPackage | null>(null)
const createdRechargeId = ref<string | null>(null)
const referenceNo = ref<string>('')

// 购买弹窗（一步）
const buyerName = ref('')
const buyerPhone = ref('')
const inputPoints = ref<number | null>(null)

function resetModalForm() {
  buyerName.value = ''
  buyerPhone.value = ''
  inputPoints.value = null
  referenceNo.value = ''
  createdRechargeId.value = null
}

async function createOrder() {
  const name = buyerName.value.trim()
  const phone = buyerPhone.value.trim()
  if (!name) { alert('구매자 성명을 입력하세요'); return }
  if (!phone || phone.length < 6 || phone.length > 20) { alert('올바른 휴대폰 번호를 입력하세요 (6-20자)'); return }

  let pts: number = 0
  if (selected.value?.id === 'custom') {
    if (!inputPoints.value || inputPoints.value <= 0) { alert('0보다 큰 원 수량을 입력하세요'); return }
    pts = Number(inputPoints.value)
  } else {
    pts = Number(selected.value?.points || 0)
    if (pts <= 0) { alert('패키지 포인트 오류'); return }
  }

  try {
    const res = await api.post('/api/pay/recharges', {
      amountDecimal: String(pts),
      pointsCredited: String(pts),
      purchaserName: name,
      purchaserPhone: phone,
    })
    if (res.ok) {
      const data = await res.json()
      createdRechargeId.value = data?.recharge?.id || null
      referenceNo.value = data?.recharge?.referenceNo || ''
      bankAccount.value = data?.account || bankAccount.value
      if (selected.value?.id === 'custom') {
        selected.value = { id: 'custom', title: `${pts} 원 (맞춤형)`, points: pts, price: pts }
      }
      // 一步实现：不切换视图，直接在同一弹窗显示参考号
    } else {
      const e = await res.json().catch(()=>({}))
      alert(e?.error || '충전 주문 생성 실패')
    }
  } catch (e: any) {
    alert(e?.message || '네트워크 오류')
  }
}

async function fetchActiveAccount() {
  try {
    const res = await api.get('/api/pay/bank-accounts/active')
    const data = await res.json()
    bankAccount.value = data?.accounts?.[0] || null
  } catch {}
}

async function openBuy(pkg: PointPackage) {
  selected.value = pkg
  showModal.value = true
}
function closeModal() {
  showModal.value = false
  resetModalForm()
}

function fmtPoints(n: number) { return n.toLocaleString() }
function fmtPrice(n: number) { return n.toLocaleString('zh-CN') }

onMounted(async () => {
  await fetchActiveAccount()
  await fetchPointPackages()
})

</script>

<template>
  <div class="layout">
    <AppHeader />

    <!-- 未登录提示 -->
    <div v-if="!auth.user" class="login-prompt">
      <div class="prompt-card">
        <h2>원 상점</h2>
        <p>로그인 후 원(선물 코인)을 구매하여 라이브 방과 채팅방에서 선물을 보낼 수 있습니다</p>
        <div class="prompt-actions">
          <button class="btn-primary" @click="router.push('/login')">지금 로그인</button>
          <button class="btn-secondary" @click="router.push('/live')">먼저 라이브 보기</button>
        </div>
      </div>
    </div>

    <!-- 已登录内容 -->
    <div v-else class="main">
      <LeftSidebar v-model="currentSection" />

      <section class="right">
        <div class="shop-page">
          <div class="shop-header">
            <h1>원 상점</h1>
            <p class="subtitle">충전 패키지를 선택하고, 시스템 지정 은행 계좌로 오프라인 송금하면 관리자 승인 후 원(선물 코인)을 지급합니다.</p>
          </div>

          <div class="toolbar">
            <div class="quick-input">
              <span>맞춤형 구매</span>
              <input type="number" min="1" :value="inputPoints ?? ''" @input="e=>{ inputPoints = Number((e.target as HTMLInputElement).value); selected = { id: 'custom', title: '맞춤형', points: 0, price: 0 } }" placeholder="원 수량" />
              <button class="primary" @click="openBuy({ id: 'custom', title: '맞춤형', points: 0, price: 0 })">즉시 구매</button>
            </div>
          </div>

          <div class="grid">
            <div v-for="pkg in pointPackages" :key="pkg.id" class="card">
              <img class="thumb" :src="pkg.img" alt="pkg" />
              <div class="title">{{ pkg.title }}</div>
              <div class="price">{{ fmtPoints(pkg.points) }} 원</div>
              <button class="buy" @click="openBuy(pkg)">즉시 구매</button>
            </div>
          </div>

          <!-- 购买弹窗（两步：填写联系人 -> 展示转账信息） -->
          <div v-if="showModal" class="modal-mask" @click.self="closeModal">
            <div class="modal">
              <div class="modal-header">
                <h3>오프라인 송금 정보</h3>
                <button class="close" @click="closeModal">✕</button>
              </div>

              <!-- 한 단계: 양식 + 은행 + 영수증 -->
              <div class="modal-body">
                <div class="section">
                  <div class="label">패키지</div>
                  <div class="value">{{ selected?.id==='custom' ? '맞춤형' : selected?.title }}</div>
                </div>
                <div class="section" v-if="selected?.id==='custom'">
                  <div class="label">원 수량</div>
                  <div class="value"><input type="number" min="1" :value="inputPoints ?? ''" @input="e=>inputPoints = Number((e.target as HTMLInputElement).value)" placeholder="원 수량을 입력하세요" /></div>
                </div>

                <!-- 은행 정보 미리 표시, 사용자가 수취 계좌 확인 편의 -->
                <div class="section">
                  <div class="label">송금 은행</div>
                  <div class="value">{{ bankAccount?.bankName }}（{{ bankAccount?.displayName }}）</div>
                </div>
                <div class="section">
                  <div class="label">계좌명</div>
                  <div class="value">{{ bankAccount?.accountName }}</div>
                </div>
                <div class="section">
                  <div class="label">계좌번호</div>
                  <div class="value">{{ bankAccount?.accountNumber }}</div>
                </div>

                <div class="section">
                  <div class="label">구매자</div>
                  <div class="value"><input type="text" :value="buyerName" @input="e=>buyerName = (e.target as HTMLInputElement).value" placeholder="성명을 입력하세요" /></div>
                </div>
                <div class="section">
                  <div class="label">휴대폰 번호</div>
                  <div class="value"><input type="text" :value="buyerPhone" @input="e=>buyerPhone = (e.target as HTMLInputElement).value" placeholder="휴대폰 번호를 입력하세요 (6-20자)" /></div>
                </div>
                <!-- 금액 (한 번만 표시) -->
                <div class="section">
                  <div class="label">금액</div>
                  <div class="value emphasis">{{ fmtPrice(selected?.id==='custom' ? (inputPoints || 0) : (selected?.price || 0)) }}</div>
                </div>

                <!-- 참조 번호 (주문 생성 후 표시) -->
                <div class="section" v-if="referenceNo">
                  <div class="label">참조 번호</div>
                  <div class="value code">{{ referenceNo }}</div>
                </div>
                <div class="hint">송금 메모에 반드시 참조 번호를 기입하고, 송금 후 관리자 승인을 기다려 원을 지급받으세요.</div>
              </div>
              <div class="modal-footer">
                <button v-if="!referenceNo" class="primary" @click="createOrder">주문 생성</button>
                <button v-else class="primary" @click="closeModal">송금 완료, 나중에 확인</button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
}

.main {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* 移动端响应式设计 */
@media (max-width: 480px) {
  .layout {
    padding-bottom: 80px; /* 为底部导航留出空间 */
  }

  .main {
    /* 在手机端，侧边栏变成固定定位，所以主内容区域占满宽度 */
    display: block;
  }
}

.login-prompt {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem;
}

.prompt-card {
  background: white;
  border-radius: 12px;
  padding: 3rem;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
}

.prompt-card h2 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.5rem;
}

.prompt-card p {
  color: #666;
  margin-bottom: 2rem;
  line-height: 1.6;
}

.prompt-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.btn-primary {
  background: #ff6b6b;
  color: white;
}

.btn-primary:hover {
  background: #ff5252;
}

.btn-secondary {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.btn-secondary:hover {
  background: #e9ecef;
}

.right {
  flex: 1;
  padding: var(--space-5);
  overflow: auto;
  background: var(--color-surface);
  color: var(--color-text);
}

.shop-page {
  padding: 0 0 var(--space-4);
}

.shop-header h1 {
  margin: 0 0 var(--space-2);
  font-size: 32px;
  font-weight: 700;
  color: var(--color-text);
}

.subtitle {
  margin-top: var(--space-2);
  color: var(--color-text-secondary);
  font-size: 16px;
  line-height: 1.6;
}

.toolbar {
  margin: var(--space-5) 0 var(--space-6);
  border: 2px dashed var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-4);
  background: var(--color-bg);
}

.quick-input {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  color: var(--color-text-secondary);
  font-weight: 500;
}

.quick-input input {
  width: 120px;
  height: 44px;
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-text);
  padding: 0 var(--space-3);
  font-size: 14px;
  transition: all 0.2s ease;
}

.quick-input input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.primary {
  background: var(--gradient-primary);
  border: 0;
  color: var(--color-text-white);
  height: 44px;
  padding: 0 var(--space-5);
  border-radius: var(--radius-md);
  cursor: pointer;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.primary:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--space-5);
}

.card {
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  padding: var(--space-5);
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: var(--shadow-sm);
  transition: all 0.2s ease;
}

.card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  border-color: var(--color-primary);
}

.thumb {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
  background: var(--color-surface);
  border: 3px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.title {
  margin-top: var(--space-4);
  font-weight: 600;
  text-align: center;
  min-height: 48px;
  color: var(--color-text);
  font-size: 16px;
  display: flex;
  align-items: center;
}

.price {
  margin-top: var(--space-2);
  color: var(--color-primary);
  font-weight: 700;
  font-size: 18px;
}

.buy {
  margin-top: var(--space-4);
  width: 100%;
  height: 44px;
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
  background: var(--color-surface);
  color: var(--color-text);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.2s ease;
}

.buy:hover {
  background: var(--color-primary-light);
  color: var(--color-primary);
  border-color: var(--color-primary);
  transform: translateY(-1px);
}

/* modal */
.modal-mask {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
  backdrop-filter: blur(4px);
}

.modal {
  width: 600px;
  max-width: calc(100% - var(--space-6));
  background: var(--color-bg);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-xl);
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--space-4) var(--space-5);
  border-bottom: 1px solid var(--color-border);
  background: var(--color-surface);
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: var(--color-text);
}

.close {
  background: transparent;
  color: var(--color-text-muted);
  border: 0;
  cursor: pointer;
  font-size: 20px;
  padding: var(--space-2);
  border-radius: var(--radius-sm);
  transition: all 0.2s ease;
}

.close:hover {
  background: var(--color-surface-hover);
  color: var(--color-text);
}

.modal-body {
  padding: var(--space-5);
}

.section {
  display: flex;
  gap: var(--space-3);
  padding: var(--space-3) 0;
  align-items: center;
}

.label {
  width: 100px;
  color: var(--color-text-secondary);
  text-align: right;
  font-weight: 500;
}

.value {
  flex: 1;
  color: var(--color-text);
}

.value input {
  width: 100%;
  height: 40px;
  padding: 0 var(--space-3);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  background: var(--color-bg);
  color: var(--color-text);
  font-size: 14px;
  transition: all 0.2s ease;
}

.value input:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(255, 107, 53, 0.1);
}

.value.emphasis {
  color: var(--color-primary);
  font-weight: 700;
  font-size: 18px;
}

.value.code {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  background: var(--color-surface);
  padding: var(--space-2) var(--space-3);
  border-radius: var(--radius-md);
  border: 1px solid var(--color-border);
  font-weight: 600;
  color: var(--color-primary);
}

.hint {
  margin-top: var(--space-4);
  color: var(--color-success);
  font-size: 14px;
  padding: var(--space-3);
  background: rgba(16, 185, 129, 0.1);
  border-radius: var(--radius-md);
  border: 1px solid rgba(16, 185, 129, 0.2);
}

.modal-footer {
  padding: var(--space-4) var(--space-5);
  border-top: 1px solid var(--color-border);
  display: flex;
  justify-content: flex-end;
  background: var(--color-surface);
}
</style>
